package store.lunangangster.engine.impl.cmd;

import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import store.lunangangster.engine.NodeFlowException;
import store.lunangangster.engine.impl.entity.ExecutionEntity;
import store.lunangangster.engine.impl.entity.mgr.ExecutionEntityManager;
import store.lunangangster.engine.impl.interceptor.CommandContext;

public class SetVariablesCmd implements Command<Void> {

  protected Map<String, Object> variables;
  protected String executionId;
  protected boolean isLocal;

  public SetVariablesCmd(Map<String, Object> variables, String executionId, boolean isLocal) {
    this.variables = variables;
    this.executionId = executionId;
    this.isLocal = isLocal;
  }

  @Override
  public Void execute(CommandContext commandContext) {
    if (variables == null || variables.isEmpty()) {
      throw new NodeFlowException("variables不能为空");
    }
    if (StringUtils.isBlank(executionId)) {
      throw new NodeFlowException("executionId不能为空");
    }

    ExecutionEntityManager executionManager = commandContext.getProcessEngineConfiguration()
        .getExecutionEntityManager();

    ExecutionEntity executionEntity = executionManager.selectById(executionId);
    if (executionEntity == null) {
      throw new NodeFlowException("找不到id为" + executionId + "的Execution");
    }
    if (isLocal) {
      executionEntity.setLocalVariables(variables);
    } else {
      executionEntity.setVariables(variables);
    }
    return null;
  }
}
